package com.wangzhenyu.common.fragment

import android.app.DatePickerDialog
import android.app.Dialog
import android.os.Bundle
import androidx.fragment.app.DialogFragment
import java.util.*

class DatePickerFragment : DialogFragment() {

    companion object {
        const val TAG = "C"
        private const val ARG_DATE_PICKER = "ARG_DATE_PICKER"
        const val ARG_DATE_PICKER_RESULT = "ARG_DATE_PICKER_RESULT"
        const val KEY_DATE_PICKER = "KEY_DATE_PICKER"

        fun newInstance(date: Date): DatePickerFragment {
            val args = Bundle().apply {
                putSerializable(ARG_DATE_PICKER, date)
            }
            return DatePickerFragment().apply {
                arguments = args
            }
        }

    }

    override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {

        val date = arguments?.getSerializable(ARG_DATE_PICKER) as Date
        val calendar = Calendar.getInstance()
        calendar.time = date

        val initialYear = calendar.get(Calendar.YEAR)
        val initialMonth = calendar.get(Calendar.MONTH)
        val initialDay = calendar.get(Calendar.DAY_OF_MONTH)

        val dateListener = DatePickerDialog.OnDateSetListener { _, i, i2, i3 ->
            val resultDate: Date = GregorianCalendar(i, i2, i3).time
            val bundle = Bundle().apply {
                putSerializable(ARG_DATE_PICKER_RESULT, resultDate)
            }
            parentFragmentManager.setFragmentResult(KEY_DATE_PICKER, bundle)
        }

        return DatePickerDialog(
            requireContext(),
            dateListener,
            initialYear,
            initialMonth,
            initialDay
        )

    }
}